
import * as zrender from '../../../../assets/js/zrender';
import * as zrhelper from '../../../../assets/js/zrender-helper';
import  {tool ,api , mta}  from '../../../../utils/quoteConfig.js'
//获取应用实例
var app = getApp();
const quote = app.globalData.quote;
// const tool = quote.tool
// const api = quote.api;
// const mta = require('../../../../utils/mta_analysis.js'); //引入腾讯埋点文件
const innerAudioContext = app.globalData.innerAudioContext; //引入音频播放器
var zr;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        url: '',
        isBrang: app.globalData.isBrang,
        gameStatus: app.globalData.gameStatus, //获取游戏状态
        main: true,
        gameOver: false,//游戏结束
        ccc: [],
        isGotoTask:false,
        index: 0,
        idx: 0,
        current: 0,
        time: 0,
        WordList: '',
        Word: '',
        GameTwoList: null,
        isShowGuidance: true,
        ChineseSentence: '',
        // animation: null,
        hash: [],
        isClickContinue: false, //防止连续点击两次
        userAnswer: [], //用户选择单词后的数组
        scale:app.globalData.scale,
        isShowEndTip:false,
        imageArr: ['../../../../src/images/yellow.png', '../../../../src/images/blue.png',
            '../../../../src/images/green.png', '../../../../src/images/white.png']
    },
    onLoad: function (options) {
        var that=this
        that.GameThreeList(2)
        that.randomCreate()
        that.setData({
            gameStatus: app.globalData.gameStatus, //获取游戏状态
        })
    },

    onReady: function () {
        var that = this;
        mta.Page.init(); //初始化腾讯埋点
        var ctx = wx.createCanvasContext('canvas-1')  
    },
    onShow: function () {
        var that=this
    },
    //开始游戏
    beginGame:function(){
        var that=this
        that.setData({
            isShowGuidance: false,
            main: true,
        })
        that.drawImg()
        that.startSetInter()
        //开始计时动画
        that.animationEnd()
    },
    onHide: function () {
        console.log('隐藏了')
    },
    onUnload: function () {
        if (zr) {
            zr.dispose();
        }
        var that=this
        //页面卸载 清除全部定时器
        clearInterval(that.data.setInter)
        clearTimeout(that.data.setTime) 
    },
    //随机气泡
    randomCreate() {
        let that = this
        let r, url;

        r = Math.floor(Math.random() * that.data.imageArr.length);
        url = that.data.imageArr[r]

        that.setData({
            url: url,
        })
        console.log(that.data.url, '107')
    },
    
    //计时
    startSetInter: function () {
        var that = this;
        that.data.setInter = setInterval(
            function () {
                that.setData({
                        time: that.data.time + 1
                });
            }, 1000);
    },
    //获取单词信息
    GameThreeList(type) {
        let that = this
        var index = that.data.index
        var dataDic = {
            GameMark: 2,
            ModuleId: app.globalData.moduleId
        };
        api.methodBasicEnglish_GetGameData({
            dataDic,
            success: function (res) {
                console.log(res)
                var data = res.data.data.GameList[index].WordList
                that.setData({
                    GameTwoList: res.data.data.GameList,
                    WordList: data,
                    Word: res.data.data.GameList[index].Word,
                    ChineseSentence: res.data.data.GameList[index].ChineseSentence,
                })
                console.log(that.data.word, '261')
                if(type==1){
                    that.drawImg()
                }else{
                    console.log('******')
                }
            }
        })
    },
    //动画
    drawImg: function () {
        var that = this
        zr = zrhelper.createZrender('canvas-1', 375, 320);   
        var image = new zrender.Image({
            style: {
                x: 0,
                y: 0,
                image: that.data.url,
                width: 70 * that.data.scale,
                height: 70 * that.data.scale,
                text: that.data.ChineseSentence,
            }
        });
        zr.add(image);
        image.animateStyle(false)
            .when(6000, {
                x: 275 * that.data.scale,
                y: 110 * that.data.scale,
            })
            .when(13000, {
                x: 10 * that.data.scale,
                y: 160 * that.data.scale,
                width: 70 * that.data.scale,
                height: 70 * that.data.scale,
            })
            .when(20000, {
                x: 275 * that.data.scale,
                y: 240 * that.data.scale,
                width: 70 * that.data.scale,
                height: 70 * that.data.scale,
            })
            .start();
    },
    //判断动画结束
    animationEnd: function () {
        this.data.setTime=setTimeout(() => {
            console.log('动画执行完毕')
            clearInterval(this.data.setInter) //清除计时器
            tool.statistics(app.globalData.openId, app.globalData.moduleId, 2, 2, 2)
            this.setData({
                gameOver: true,
                isShowEndTip: false
            })
        }, 20000)
    },
   //点击结束游戏按钮
    endTask() {
        let that = this
        that.setData({
            isShowEndTip:true,
        })
    },
    //结束游戏再想想
    endGameCacel() {
        let that = this
        that.setData({
            isShowEndTip:false
        })
    },
    //结束游戏确定
    endGameConfim() {
        let that = this
        wx.redirectTo({
            url: '/pages/indexPackage/courseList/courseList',
        })
        tool.statistics(app.globalData.openId, app.globalData.moduleId, 2, 2, 1)
    },

    //游戏失败重新挑战
    challengeAgain() {
        console.log('任务失败重新挑战')
        let that = this
        that.setData({
            index: 0,
            gameOver: false,
            time:0,
            userAnswer:[],
        })
        var ctx1 = wx.createCanvasContext('canvas-1')
        ctx1.clearRect(0, 0, 375, 320) 
        that.GameThreeList(1)
        that.startSetInter()
        that.animationEnd()
    },
    //游戏失败休息一会在战  
    rest:function(){
        if(app.globalData.addId == 0){
            app.globalData.addId = 1
            
           wx.reLaunch({
             url: '../../../../pages/indexPackage/courseList/courseList?addId='+ 1,
           })
         }else{
           console.log('走缓存处理')
           wx.getStorage({
             key: 'removes',
             success: (res) => {
               console.log(res.data)
               if(res.data){
                 console.log('426')
                 wx.reLaunch({
                   url: '../../../../pages/indexPackage/courseList/courseList?addId=' + 2,
                 })
               }
             },
         
           })
         }
    },
    //通关休息一会儿
    restTime:function(){
        var that=this
        that.unlockLevels(2)
    },
    //进入下一节
    gotoTask:function(){
        var that=this
        that.unlockLevels(1)
    },
    //解锁
    unlockLevels: function (type) {
        var dataDic = {
            SubtitleId: 3,
            ModuleId: app.globalData.moduleId,
            OpenId: app.globalData.openId
        };
        var that = this
        api.methodBasicEnglish_Unlock({
            dataDic: dataDic,
            success: function (res) {
                console.log('解锁成功', res)
                if(type==1){
                    that.getTaskStatus()
                }else if(type ==2){
                    if(app.globalData.addId == 0){
                        app.globalData.addId = 1
                        
                       wx.redirectTo({
                         url: '../../../../pages/indexPackage/courseList/courseList?addId='+ 1,
                       })
                     }else{
                       console.log('走缓存处理')
                       wx.getStorage({
                         key: 'removes',
                         success: (res) => {
                           console.log(res.data)
                           if(res.data){
                             console.log('426')
                             wx.redirectTo({
                               url: '../../../../pages/indexPackage/courseList/courseList?addId=' + 2,
                             })
                           }
                         },
                     
                       })
                     }
                }
              
            },
            fail: function (err) {
                console.log('解锁失败', err)
            }
        })

    },
    //选择单词
    clickWord(e) {
        let that = this
        var hash = that.data.hash
        var userArr = that.data.userAnswer
        var text = e.currentTarget.dataset.text
        var idex = e.currentTarget.dataset.indx
        var index = that.data.index
        var ccc = that.data.ccc
        if (that.data.isClickContinue) {
            console.log('防止连续点击')
            return
        }
        var json = {
            text: text,
            id: idex //点击还原原来位置的标识
        }
        var WordList = that.data.WordList
        WordList.splice(idex, 1, '')
        that.setData({
            WordList: WordList,
            isClickContinue: true,
            current: idex,
        })
        var newWordList = that.data.WordList.join('')
        if (newWordList == '') {
            console.log('题目被点完了')
        } else {
            console.log('没有被点完')
            that.setData({
                isClickContinue: false,
            })
        }
        userArr.push(json)
        // 当点击的是当前元素的时候，退出
        if (~userArr.indexOf(index)) {
            return;
        }
        that.setData({
            userAnswer: userArr
        })
        var aaa = that.data.userAnswer
        if (newWordList == '') {
            console.log('填满了')
            for (var i = 0; i < that.data.userAnswer.length; i++) {
                ccc.push(that.data.userAnswer[i].text)
            }
            var ddd = ccc.join('')
            var bbb = that.data.Word
            if (ddd === bbb) { //答题正确
                console.log('答题正确')
                clearInterval(that.data.setInter) //清除计时器
                innerAudioContext.src = '/src/record/true1.mp3'
                innerAudioContext.play()
                if (index == that.data.GameTwoList.length - 1) { //最后一题
                    console.log(that.data.time, '统计学习时间')
                    clearTimeout(that.data.setTime) 
                    var time=that.data.time
                    var courseName = app.globalData.courseName
                    var timeStr = '0~10'
                    if (time > 0 && time <= 10) {
                        timeStr = '0~10'
                    } else if (time > 10 && time <= 15) {
                        timeStr = '11~15'
                    } else if (time > 15 && time <= 25) {
                        timeStr = '16~25'
                    } else if (time > 25 && time <= 30) {
                        timeStr = '26~30'
                    } else {
                        timeStr = '30以上'
                    }
                    app.aldstat.sendEvent('通关时长', { 'duration': courseName + '-游戏2-通关时长-' + timeStr });
                    mta.Event.stat("duration_statistics", { 'duration': courseName + '-游戏2-通关时长-' + timeStr});
                    innerAudioContext.src = '/src/record/true1.mp3'
                    innerAudioContext.play()                   
                    that.setData({
                      main: false,
                      isGotoTask: true
                  })
                } else {
                    var index2 = index + 1
                    that.setData({
                        Word: that.data.GameTwoList[index2].Word,
                        ChineseSentence: that.data.GameTwoList[index2].ChineseSentence,
                        WordList: that.data.GameTwoList[index2].WordList,
                        index: index2,
                        userAnswer: [],
                        ccc: [],
                        isClickContinue: false
                    })
                    zr.dispose();
                    var ctx1 = wx.createCanvasContext('canvas-1')
                    ctx1.clearRect(0, 0, 375, 320)
                    clearTimeout(that.data.setTime) 
                    that.startSetInter()
                    that.drawImg()
                    that.animationEnd() 
                    that.randomCreate()                  
                }
            } else {
                console.log('答案错误')
                console.log(that.data.index, '376')
                innerAudioContext.src = '/src/record/false.mp3'
                innerAudioContext.play()
                that.setData({
                    Word: that.data.GameTwoList[index].Word,
                    WordList: that.data.GameTwoList[index].WordList,
                    userAnswer: [],
                    ccc: [],
                    isClickContinue: false
                })
            }
        }
    },
    //点击选择好的单词
    clickF(e) {
        let that = this
        var num = e.currentTarget.dataset.num
        var current = that.data.current
        var text = e.currentTarget.dataset.text
        var idex = e.currentTarget.dataset.indx
        var userAnswer = that.data.userAnswer
        var WordList = that.data.WordList
        if (num != undefined) {
            WordList.splice(num, 1, text)
        }
        userAnswer.splice(idex, 1)

        that.setData({
            WordList: WordList,
            userAnswer: userAnswer,
        })
        console.log(that.data.userAnswer, '433')
    },

    //获取任务状态
    getTaskStatus: function () {
        var that = this
        var dataDic = {
            ModuleId: app.globalData.moduleId,
        };
        api.methodBasicEnglish_GetTask({
            dataDic: dataDic,
            success: function (res) {
                console.log('数据请求成功', res)
                app.globalData.taskStatus = res.data.data
                if (res.data.data.TaskOne == true) {
                    wx.reLaunch({
                        url: '/pages/taskPackage/pages/taskOne/taskOne',
                    })
                    return
                } else if (res.data.data.TaskTwo == true) {
                    wx.reLaunch({
                        url: '/pages/taskPackage/pages/taskTwo/taskTwo',
                    })
                    return
                } else if (res.data.data.TaskThree == true) {
                    wx.reLaunch({
                        url: '/pages/taskPackage/pages/taskThree/taskThree',
                    })
                    return
                } else if (res.data.data.TaskFour == true) {
                    wx.reLaunch({
                        url: '/pages/taskPackage/pages/taskFour/taskFour',
                    })
                    return
                }
            },
            fail: function (err) {
                console.log('数据请求失败', err)
            }
        })

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        return {
            path: 'pages/indexPackage/index/index',
            success: function (res) {
                console.log('转发成功', res);
            },
            fail: function (err) {
                console.log('转发失败', err)
            }
        }
    }

})